Skip to main content

Class: ContactManager

The ContactManager class is responsible for managing connections (contacts) within the One37ID platform. It provides a range of methods for tasks like adding, removing, and listing contacts, as well as verifying emails and retrieving connection flows.


Method: startEmailVerificationFlow

Starts the process to verify an email. A verification link is sent to the provided email address, and the user must click the link to complete the verification.

note

You should add a connection first in order for the verification process works.

  • Parameters:
    • email: string — The email address to verify.
  • Returns: Promise<void> — Returns a promise that resolves when the verification link is sent successfully.
const homeResult = await agent.contactManager.addHome();
const result = await agent.contactManager.startEmailVerificationFlow(email);

Usage Example

const homeResult = await agent.contactManager.addHome();
if (homeResult.isSuccessful) {
const result = await agent.contactManager.startEmailVerificationFlow(
"user@example.com"
);
console.log("Verification link sent to the email");
}

Example Output

{ "isSuccessful": true }

Method: addHome

Adds a default connection to a platform based on the Agent Configuration provided during initialization. This method establishes a secure connection with a service or organization, enabling interaction with that entity.

For instance, if the agent configuration includes the following agentInfo, it will connect to One37ID:

export const telusagentInfo = {
name: "HealthID",
alias: "z6LSohkq71MLbeyUEhW6bqWF3HtsLogucgrmMttuiND1d1iw",
linkedDomain: "https://healthid.dev-one37.id",
};

This means the agent will establish a connection with HealthID on the One37ID platform.

  • Parameters: None
  • Returns: Promise<ConnectionResult> — Returns the connection result, which includes metadata about the connection, such as the base URL, connection status, and other details.
const connectionResult = await agent.contactManager.addHome();

Usage Example

const connectionResult = await agent.contactManager.addHome();
if (connectionResult.isSuccessful) {
console.log("Connected to", connectionResult.result.displayName);
}

Example Output

{
"isSuccessful": true,
"result": {
"baseUrl": "https://137.dev-one37.id",
"connectionStatus": "completed",
"displayName": "One37 Solutions, Inc.",
"id": "2921ab55-48da-4a47-9684-a75f1ea0c7d2",
"logoUrl": "https://cdn.one37id.com/static/images/one37.png",
"metadata": {
"alias": "did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"privacyPolicy": "https://www.one37id.com/resources/privacy.html",
"support": "support@one37id.com",
"title": "One37 Solutions, Inc."
},
"myAlias": "did:one37:com.one37id:default:cc2bb92c-7711-4b1b-ab7a-ece53dfc73f9"
}
}

This clarifies that the connection is based on the agent configuration (agentInfo) and will connect to different services based on the values provided during initialization. If the configuration points to One37ID, it will connect to One37 Solutions, Inc., or otherwise to the relevant service if a different configuration is used.---


Method: getHome

The getHome() method retrieves the default connection to One37 Solutions, Inc. This method is essential when interacting with the One37ID platform, as it provides the default, pre-established connection with One37 Solutions, Inc. for further communications or operations.

  • Parameters: None
  • Returns: Promise<ConnectionResult> — Resolves to a ConnectionResult object, containing detailed information about the connection to One37 Solutions, Inc. including metadata, DID, alias, and more.

Usage Example

const result = await agent.contactManager.getHome();
console.log("Connection to One37 Solutions, Inc. retrieved:", result);

Example Output

{
"isSuccessful": true,
"result": {
"baseUrl": "https://137.dev-one37.id",
"connectionStatus": "completed",
"displayName": "One37 Solutions, Inc.",
"id": "18034a83-8b1e-4c05-ae75-5fc9d183d8c7",
"logoUrl": "https://cdn.one37id.com/static/images/one37.png",
"metadata": {
"alias": "did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"privacyPolicy": "https://www.one37id.com/resources/privacy.html",
"support": "support@one37id.com",
"title": "One37 Solutions, Inc.",
"isTrusted": false,
"minConsentLevel": 4,
"nym": "z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"publicHostNames": [],
"updateDate": "2024-10-04T08:17:30.479Z",
"website": "https://137.dev-one37.id/bc/public"
},
"myAlias": "did:one37:com.one37id:default:890686f0-45a4-4590-9127-c6f7a87aaf1e",
"myDid": "did:peer:2.Ez6LSiLByajVShHNY7Zqd3P4sPgcqPajfGtc7bbRWdidzQtFh.Vz6MkgXSoG5j14tJb8BZmZEDQqN6zHJEfHU4RSHMGFoA65Vva.SeyJpZCI6IjFkOTM2NDdhLTkwNDMtNGYzNi04NzczLTFhODNhYTExNjVhZiIsInQiOiJkbSIsInMiOiIifQ",
"theirAlias": "did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"theirDid": "did:web:137.dev-one37.id"
}
}

Method: getList

Retrieves a paginated list of all connections (contacts).

  • Parameters:
    • currentPage: number — The page number to retrieve.
    • rowsPerPage: number — The number of rows to retrieve per page.
  • Returns: Promise<ConnectionList> — Returns a list of contacts (connections) with metadata.
const connections = await agent.contactManager.getList({
currentPage: 1,
rowsPerPage: 1000,
});

Usage Example

const connections = await agent.contactManager.getList({
currentPage: 1,
rowsPerPage: 100,
});
console.log("Connections retrieved: ", connections);

Example Output

{
"currentPage": 1,
"pagesCount": 1,
"result": [
{
"baseUrl": "https://137.dev-one37.id",
"connectionStatus": "completed",
"displayName": "One37 Solutions, Inc.",
"id": "2921ab55-48da-4a47-9684-a75f1ea0c7d2",
"myAlias": "did:one37:com.one37id:default:cc2bb92c-7711-4b1b-ab7a-ece53dfc73f9"
}
],
"rowsCount": 1,
"rowsPerPage": 1
}

Method: getByAlias

The getByAlias() method retrieves a connection (contact) using an alias or realm. This is useful when you need to locate a specific contact in your system based on an alias or realm.

  • Parameters:
    • model: AliasIdentifier — An object containing either an alias or realm (or both) to identify the contact. The AliasIdentifier type consists of:
      • alias?: string — The alias of the contact to search for.
      • type?: AliasType — (Optional) The type of alias being searched.
      • realm?: string — The realm in which the alias exists.

Note: Either alias or realm must be provided. If both are omitted, an error is returned.

  • Returns: Promise<OperationDataResult<Contact>> — Resolves to an OperationDataResult object containing the contact details if found, or an error message if not.

Usage Example

To find a connection using either an alias or realm, you can call the getByAlias() method and pass in the AliasIdentifier model:

// Example with alias only
const model = {
alias:
"did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
};

const result = await agent.contactManager.getByAlias(model);
console.log("Connection found:", result);

Or, if you need to specify a realm:

// Example with alias and realm
const model = {
alias:
"did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
realm: "exampleRealm",
};

const result = await agent.contactManager.getByAlias(model);
console.log("Connection found:", result);

Example Output

{
"isSuccessful": true,
"result": {
"id": "499c1468-37ad-4b95-926e-855713395863",
"alias": "johnDoeAlias",
"realm": "exampleRealm",
"connectionStatus": "completed",
"metadata": {
"title": "John Doe",
"nym": "z6MkgXSoG5j14tJb8BZmZEDQqN6zHJEfHU4RSHMGFoA65Vva",
"createdDate": "2024-10-04T08:17:30.479Z"
}
}
}

Method: addByAlias

Adds a contact (connection) by alias. If the alias exists, the SDK waits for user confirmation before completing the addition.

  • Parameters:
    • realm: string — The alias of the contact to add.
    • myAlias?: string — Optionally provide a personal alias for the contact.
  • Returns: Promise<void> — Returns a promise that resolves after the alias has been added or the user declines.
const addContactByAlias = await agent.contactManager.addByAlias({
realm: "aliasName",
});

Usage Example

const addContactByAlias = await agent.contactManager.addByAlias({
realm: "johnDoeAlias",
});
console.log("Contact added by alias, awaiting user confirmation");

Example Output

{ "isSuccessful": true }

Method: get

The get() method is used to find and retrieve contact details by using various search criteria (such as contact ID, alias, or DID). This method allows you to locate a specific contact (connection) based on the provided contactFilter and returns detailed information about the contact.

  • Purpose: The purpose of the get() method is to search for and retrieve a contact's details by applying different filters. It helps in identifying contacts based on their ID, alias, DID, or other relevant attributes and returns the corresponding contact information.

  • Parameters:

    • contactFilter: ContactFilterModel — The search criteria used to find the contact. This model can contain:
      • id?: string — The unique identifier of the contact.
      • alias?: AliasIdentifier — The alias of the contact.
      • defaultAlias?: string — The default alias of the contact.
      • baseUrl?: string — The base URL related to the contact.
      • did?: string — The decentralized identifier (DID) of the contact.
  • Returns: Promise<OperationDataResult<Contact>> — Resolves to an OperationDataResult object that contains the contact details if successful. If the contact is not found or if there is an error, it returns false with an error message.

Usage Example

This example demonstrates how to use the get() method to retrieve contact details by providing a specific contactFilter.

export const getContactDetails = async (): Promise<void> => {
try {
const agent = await initializeAgent();
if (!agent) {
throw new Error("Agent not initialized");
}

// Define the contact filter with the contact ID
const contactFilter = { id: "18034a83-8b1e-4c05-ae75-5fc9d183d8c7" }; //replace the id with the actual contact ID

// Fetch the contact details using the get method
const result = await agent.contactManager.get(contactFilter);

if (!result.isSuccessful) {
console.error(
`Failed to find contact. Status: ${result.errorCode}. Error: ${result.error}`
);
} else {
console.info(
`Contact details retrieved: ${JSON.stringify(result.result)}`
);
}
} catch (error) {
console.log("Error retrieving contact details:", error);
}
};

Example Output (Success)

{
"isSuccessful": true,
"result": {
"id": "d1f25b22-b098-4169-b3a0-ee8b3d0eacf7",
"displayName": "One37 Solutions, Inc.",
"connectionStatus": "completed",
"metadata": {
"alias": "did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"privacyPolicy": "https://www.one37id.com/resources/privacy.html",
"support": "support@one37id.com",
"title": "One37 Solutions, Inc."
}
}
}

Method: delete

Removes a contact (connection) from the agent.

  • Parameters:

    • contact: Contact — The contact object to remove.
  • Returns: Promise<void> — Returns a promise that resolves once the contact is removed.

  • Contact Object Example:

{
"isSuccessful":true,
"result":{
"baseUrl":"https://137.dev-one37.id",
"connectionStatus":"completed",
"displayName":"One37 Solutions, Inc.",
"id":"2921ab55-48da-4a47-9684-a75f1ea0c7d2",
"logoUrl":"https://cdn.one37id.com/static/images/one37.png",
"metadata":{
"alias":"did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"copyright":"© 2024 One37 Solutions, Inc. All Rights Reserved.",
"did":"did:web:137.dev-one37.id",
"isTrusted":true,
"logoUrl":"https://cdn.one37id.com/static/images/one37.png",
"minConsentLevel":4,
"nym":"z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"privacyPolicy":"https://www.one37id.com/resources/privacy.html",
"publicHostNames":[
"Array"
],
"support":"support@one37id.com",
"title":"One37 Solutions, Inc.",
"updateDate":"2024-10-03T07":"44":39.993Z,
"website":"https://137.dev-one37.id/bc/public"
},
"myAlias":"did:one37:com.one37id:default:cc2bb92c-7711-4b1b-ab7a-ece53dfc73f9",
"myDid":"did:peer:2.Ez6LSrwAMGG17bgeXmdfWBRfhiLtnFrw5nwhGCve2ikbWGXB6.Vz6MkvnnsbZqZrjoPAKR1zvUoGbt4YDiqHYZ2W9fkYqP6yBGm.SeyJpZCI6IjhmMDIzZjNmLWFjNzAtNDM0MS1hM2Q5LTJiZjJmMjM2NWU5ZCIsInQiOiJkbSIsInMiOiIifQ",
"theirAlias":"did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"theirDid":"did:web:137.dev-one37.id"
}
}
await agent.contactManager.delete(contact);

Usage Example

await agent.contactManager.delete(contact);
console.log("Contact deleted");

Example Output

{ "isSuccessful": true }

Method: fetchBusinessData

The fetchBusinessData() method is an internal function that retrieves business data, such as flows and UI templates, from the server and stores it on the user's wallet. This data is essential for interacting with business-specific functionalities like workflows. After fetching, the developer can use the getFlows() method to retrieve the data directly from the wallet.

info

This method is planned to be automated in future versions of the SDK.

  • Parameters:
    • contactFilter: ContactFilterModel — The filter object that can contain properties such as id, alias, defaultAlias, baseUrl, and did to identify the contact.
    • areaType?: BusinessDataAreaType[] — Area type(s) for the flow: 1 for Production, 2 for Stage, and 3 for Development.
  • Returns: Promise<FlowResult[]> — Resolves to an array of flow results (FlowResult[]) containing the available business workflows for the contact.

Usage Example

const connection = await agent.contactManager.getHome(); // Retrieve home connection
const connectionId = connection.result.id; // Extract connection ID

// Fetch business data flows for production and stage environments
const flows = await agent.contactManager.fetchBusinessData(
{ id: connectionId },
[1, 2]
);

console.log("Flows available for this connection:", flows);

Method: getFlows

Retrieves the available workflows (flows) for a specific connection (contact).

note

You need to make sure to call fetchBusinessData to fetch data before using this function.

  • Parameters:
    • contactFilter: ContactFilterModel — The filter object that can contain id, alias, defaultAlias, baseUrl, and did.
    • areaType?: BusinessDataAreaType[] — Area type(s) for the flow: 1 for Production, 2 for Stage, and 3 for Development.
  • Returns: Promise<FlowResult[]> — Returns a list of available flows for the contact.
const flows = await agent.contactManager.getFlows({ id: connectionId }, [1, 2]);

Usage Example

const connection = await agent.contactManager.getHome();
const connectionId = connection.result.id;
const flows = await agent.contactManager.getFlows({ id: connectionId }, [1, 2]);
console.log("Flows available for this connection:", flows);

Example Output

{
"isSuccessful": true,
"result": [
{
"areaType": 1,
"contactId": "18034a83-8b1e-4c05-ae75-5fc9d183d8c7",
"namespace": "com.address",
"title": "Address",
"version": 2
},
{
"areaType": 1,
"contactId": "18034a83-8b1e-4c05-ae75-5fc9d183d8c7",
"namespace": "com.amount",
"title": "Amount",
"version": 2
}
]
}

Method: addByDid

The addByDid() method establishes a connection with a user or entity using their Decentralized Identifier (DID). This method allows you to create secure, decentralized connections by leveraging the DID system.

  • Parameters:
    • did: string — The Decentralized Identifier of the entity to connect with (e.g., did:web:example.com).
    • myAlias?: string — (Optional) A personal alias you can assign to this connection for easier identification.
  • Returns: Promise<ConnectionResult> — Resolves to a ConnectionResult object containing details of the newly created connection.

Usage Example

const connection = await agent.contactManager.addByDid(
"did:web:stream.dev-one37.id"
);
console.log("Connection established:", connection);

Example Output

{
"isSuccessful": true,
"result": {
"did": "did:web:stream.dev-one37.id",
"alias": "stream.dev-one37",
"connectionStatus": "pending",
"metadata": {
"createdDate": "2024-10-03T09:00:00.000Z",
"myAlias": "myCustomAlias",
"theirAlias": "streamAlias",
"title": "Stream Connection"
}
}
}

Method: runFlow

The runFlow() method executes a specified flow for a contact (connection). This method is used to initiate workflows (flows) associated with a contact, such as forms, processes, or interactions within the One37ID platform.

Example Flow Object:

{
"areaType": 1,
"contactId": "499c1468-37ad-4b95-926e-855713395863",
"namespace": "com.address",
"title": "Address",
"version": 2
}
  • Parameters:
    • contactId: string — The ID of the contact (connection) with whom the flow will be run.
    • namespace?: string — The namespace of the flow (e.g., "com.address"). This identifies the specific workflow to run.
    • version: number — The version of the flow item to run. By default, the latest version will be used if not provided.
  • Returns: Promise<FlowResult> — Resolves to a FlowResult object indicating the success of the flow execution.

Usage Example

const contactId = "499c1468-37ad-4b95-926e-855713395863";
const namespace = "com.address";
const version = 2;

const result = await agent?.contactManager.runFlow(
contactId,
namespace,
version
);
console.log("Flow execution result:", result);

Example Output

{
"isSuccessful": true
}

Method: fetchInbox

The fetchInbox() method retrieves inbox messages for a specified contact (connection). This function is useful when you need to access messages or notifications that are associated with a particular contact in the One37ID platform.

  • Purpose: The purpose of fetchInbox() is to find a connection (contact) and fetch its associated inbox messages. These messages can be any form of communication or notifications related to the contact.

  • Parameters:

    • contactFilter: ContactFilterModel — A filter object that helps identify the contact whose inbox you want to fetch. The ContactFilterModel can contain:
      • id?: string — The unique ID of the contact.
      • alias?: AliasIdentifier — The alias of the contact.
      • defaultAlias?: string — The default alias associated with the contact.
      • baseUrl?: string — The base URL related to the contact.
      • did?: string — The decentralized identifier (DID) of the contact.
  • Returns: Promise<OperationResult> — Resolves to an OperationResult object that indicates whether the inbox messages were successfully fetched. If successful, it returns true, otherwise it returns false with an error message and error code.

Usage Example

// Define the contact filter using the contact ID or DID
const contactFilter = { id: "18034a83-8b1e-4c05-ae75-5fc9d183d8c7" };

// OR
// const contactFilter = { did: "did:web:137.dev-one37.id" };

// Fetch the inbox messages for the contact
const inboxResult = await agent.contactManager.fetchInbox(contactFilter);

if (inboxResult.isSuccessful) {
console.log("Inbox messages fetched successfully");
} else {
console.error("Failed to fetch inbox:", inboxResult.error);
}

Example Output (Success)

{
"isSuccessful": true
}

Method: refreshProfile

The refreshProfile() method is used to update or refresh the business profile of a contact from a remote source. This method allows you to sync the latest information about a contact (e.g., company or individual) by fetching updated data from an external source and updating the local profile stored within your system.

  • Purpose: The purpose of the refreshProfile() function is to ensure that the contact's business profile is up-to-date. This is particularly useful if the contact's information might have changed on the remote source, and you want to retrieve the most recent details, such as contact information, metadata, or other relevant business data.

  • Parameters:

    • model: ContactFilterModel — The search criteria used to identify the contact whose profile should be refreshed. This model can contain the following fields:
      • id?: string — The unique ID of the contact.
      • alias?: AliasIdentifier — The alias associated with the contact.
      • defaultAlias?: string — The default alias of the contact.
      • baseUrl?: string — The base URL related to the contact.
      • did?: string — The decentralized identifier (DID) of the contact.
  • Returns: Promise<OperationDataResult<Contact>> — Resolves to an OperationDataResult object that indicates whether the operation was successful. If successful, the updated contact details are returned.

Usage Example

// Define the contact filter using contact ID or alias
const contactFilter = { id: "18034a83-8b1e-4c05-ae75-5fc9d183d8c7" };

// Call refreshProfile to update the contact's business profile
const result = await agent.contactManager.refreshProfile(contactFilter);

if (result.isSuccessful) {
console.log("Contact profile refreshed successfully:", result);
} else {
console.error("Failed to refresh profile:", result);
}

Example Output (Success)

{
"isSuccessful":true,
"result":{
"baseUrl":"https://137.dev-one37.id",
"connectionStatus":"completed",
"displayName":"One37 Solutions, Inc.",
"id":"18034a83-8b1e-4c05-ae75-5fc9d183d8c7",
"logoUrl":"https://cdn.one37id.com/static/images/one37.png",
"metadata":{
"alias":"did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"copyright":"©2024 One37 Solutions, Inc. All Rights Reserved.",
"did":"did:web:137.dev-one37.id",
"isTrusted":false,
"logoUrl":"https://cdn.one37id.com/static/images/one37.png",
"minConsentLevel":4,
"nym":"z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"privacyPolicy":"https://www.one37id.com/resources/privacy.html",
"publicHostNames":[
"Array"
],
"support":"support@one37id.com",
"title":"One37 Solutions, Inc.",
"updateDate":"2024-10-07T07":"33":11.443Z,
"website":"https://137.dev-one37.id/bc/public"
},
"myAlias":"did:one37:com.one37id:default:890686f0-45a4-4590-9127-c6f7a87aaf1e",
"myDid":"did:peer:2.Ez6LSiLByajVShHNY7Zqd3P4sPgcqPajfGtc7bbRWdidzQtFh.Vz6MkgXSoG5j14tJb8BZmZEDQqN6zHJEfHU4RSHMGFoA65Vva.SeyJpZCI6IjFkOTM2NDdhLTkwNDMtNGYzNi04NzczLTFhODNhYTExNjVhZiIsInQiOiJkbSIsInMiOiIifQ",
"theirAlias":"did:one37:com.one37id:default:z6LSqn4be5EfDDaAWGbi9AsesJzq6C6eS8wN513v7794ZYQP",
"theirDid":"did:web:137.dev-one37.id"
}
}

Method: setDeviceToken

The setDeviceToken() method is used to store a device token for a contact, allowing the system to send push notifications to that device. This function is particularly useful for enabling push notifications (e.g., FCM tokens) for a specific contact in the One37ID platform.

  • Purpose: The primary purpose of this method is to link a device's token (e.g., a Firebase Cloud Messaging (FCM) token) with a contact. Once the token is stored, the contact can receive push notifications.

  • Parameters:

    • contactFilter: ContactFilterModel — The search criteria used to identify the contact. This model can contain:

      • id?: string — The unique ID of the contact.
      • alias?: AliasIdentifier — The alias associated with the contact.
      • defaultAlias?: string — The default alias of the contact.
      • baseUrl?: string — The base URL related to the contact.
      • did?: string — The decentralized identifier (DID) of the contact.
    • deviceInfo: SetDeviceTokenPayload — The device information, including:

      • vendor: DeviceVendor — The type of device (e.g, IOS, ANDROID)
      • token: string — The device token used to send push notifications.
  • Returns: Promise<OperationResult> — Resolves to an OperationResult object, indicating whether the device token was successfully stored or if an error occurred.

Usage Example

// Define the contact filter to identify the contact
const contactFilter = { id: "18034a83-8b1e-4c05-ae75-5fc9d183d8c7" };

// Define the device token payload with vendor and token
const deviceInfo = {
vendor: "IOS", //IOS Device
token: "abcd1234exampletoken",
};

// Call setDeviceToken to store the device token for push notifications
const result = await agent.contactManager.setDeviceToken(
contactFilter,
deviceInfo
);

if (result.isSuccessful) {
console.log("Device token stored successfully for push notifications.");
} else {
console.error("Failed to store device token:", result.error);
}

Example Output (Success)

{
"isSuccessful": true
}

Common Use Cases

  • Enabling Push Notifications: When a user logs into your application or registers a new device, you can store the device's notification token using this method. This ensures that push notifications, such as real-time updates or alerts, can be sent to the user's device.
  • Updating Device Tokens: If a device token changes (e.g., after an app reinstall or device reset), this method can be used to update the token associated with a contact.

Method: resumeFlow

The resumeFlow() method is used to resume a paused or interrupted business flow. Business flows represent specific processes or workflows within your application that can be paused and later resumed. This method ensures that the flow can be resumed from where it was stopped, using a correlation identifier, contact details, and other relevant flow information.

  • Purpose: The purpose of this method is to restart a business flow that was paused or interrupted. It fetches the flow's source code and uses it to resume the workflow associated with a specific contact.

  • Parameters:

    • correlationId: string — The unique correlation identifier used to link the flow with a specific instance of the workflow.
    • contactId: string — The unique identifier for the contact (connection) related to the flow.
    • namespace: string — The namespace that defines the flow type or category.
    • version: number — The version of the flow to resume.
    • payload?: any — (Optional) Additional data or parameters required to resume the flow.
  • Returns: Promise<OperationResult> — Resolves to an OperationResult object indicating whether the flow was successfully resumed. If successful, it returns true; otherwise, it returns false with an error message.

Usage Example

// Define the correlation ID, contact ID, flow namespace, and version
const correlationId = "12345";
const contactId = "18034a83-8b1e-4c05-ae75-5fc9d183d8c7";
const namespace = "com.example.business";
const version = 2;

// Optionally, define a payload if needed for the flow
const payload = {
additionalData: "value",
};

// Call resumeFlow to resume the paused business flow
const result = await agent.contactManager.resumeFlow(
correlationId,
contactId,
namespace,
version,
payload
);

if (result.isSuccessful) {
console.log("Business flow resumed successfully.");
} else {
console.error("Failed to resume business flow:", result.error);
}

Example Output (Success)

{
"isSuccessful": true
}

Common Use Cases

  • Resuming Paused Workflows: When a user leaves a process unfinished or a flow is paused (e.g., an application process or approval workflow), this method allows you to resume the flow from where it was left off.
  • Error Recovery: If a business flow was interrupted due to a system failure or user error, this method can be used to resume the workflow without starting from the beginning.

Method: startFlow

The startFlow() method is used to initiate a new business flow or process based on specific criteria and arguments. This method allows you to trigger a flow for a contact by specifying a URL endpoint and optional request payload. Flows represent processes that can be started for a specific contact, and this method ensures the appropriate flow is invoked.

  • Purpose: The purpose of the startFlow() method is to initiate a business flow or request, such as fetching aliases, adding new data, or providing consent for a contact. The method handles locating the contact, preparing the request, and invoking the flow through the provided URL.

  • Parameters:

    • contactFilter: ContactFilterModel — The search criteria used to identify the contact (connection) for whom the flow is being initiated. This model can contain:

      • id?: string — The unique identifier of the contact.
      • alias?: AliasIdentifier — The alias of the contact.
      • did?: string — The decentralized identifier (DID) of the contact.
    • args: { url: string, useBEEngine?: boolean, payload?: any } — The arguments for starting the flow:

      • url: string — The URL endpoint where the flow is triggered.
      • useBEEngine?: boolean — (Optional) Whether to use the backend engine for flow execution.
      • payload?: any — (Optional) Additional data or parameters required for the flow.
  • Returns: Promise<OperationResult> — Resolves to an OperationResult object indicating whether the flow was successfully initiated. If successful, it returns true; otherwise, it returns false with an error message.

Usage Example

  1. Fetching Aliases

This example demonstrates how to use startFlow() to initiate a flow to fetch aliases for a specific contact.

export const getAliases = async (): Promise<boolean> => {
try {
const agent = await initializeAgent();
if (!agent) {
throw new Error("Agent not initialized");
}

// Start the flow to fetch aliases
const result = await agent.contactManager.startFlow(
{ id: "d1f25b22-b098-4169-b3a0-ee8b3d0eacf7" },
{
requestId: "cdscds-b098-4169-b3a0-ee8b3d0eacf7",
url: "ars/alias/list/",
}
);

if (!result.isSuccessful) {
console.error(`[BASIC MESSAGE] Error: ${result.error}`);
return false;
} else {
console.info(`Alias fetch requested`);
console.log("Fetch alias response:", result);
return true;
}
} catch (error) {
console.log("Fetch alias error:", error);
return false;
}
};
  1. Adding a New Alias

In this example, startFlow() is used to create a new alias for a contact.

export const addNewAlias = async (alias: string): Promise<boolean> => {
try {
const agent = await initializeAgent();
if (!agent) {
throw new Error("Agent not initialized");
}

// Start the flow to add a new alias
const result = await agent.contactManager.startFlow(
{ id: "d1f25b22-b098-4169-b3a0-ee8b3d0eacf7" },
{
requestId: "dsadsadsa-b098-4169-b3a0-ee8b3d0eacf7",
url: "ars/alias/add/",
myAlias: alias,
}
);

if (!result.isSuccessful) {
console.error(`[BASIC MESSAGE] Error: ${result.error}`);
return false;
} else {
console.info(`Alias '${alias}' successfully created.`);
console.log("Add alias response:", result);
return true;
}
} catch (error) {
console.log("Add alias error:", error);
return false;
}
};
  1. Adding Consent

This example demonstrates how to use startFlow() to add consent for a contact.

export const addConsent = async (alias: string): Promise<void> => {
const agent = await initializeAgent();
if (!agent) {
throw new Error("Agent not initialized");
}
let response = await agentInstance.contactManager.getHome;
let connection = response.result;

const url = "consent/add";
const payloadx = {
customerBaseUrl: "https://clinic37-idnext.dev-one37.id",
schemaName: "schema.com.telus.services.userconsent",
schemaVersion: "1.0",
_namespace: "personal.telus.user.consent.receipt",
customer: "clinic37",
};

console.log("addConsent:", payloadx);
console.log("connection:", connection);

const result = await agent.contactManager.startFlow(
{ id: connection?.id },
{
requestId: "some_unique_iddsadsaSAsa",
url: url,
useBEEngine: false,
payload: payloadx,
}
);

if (!result.isSuccessful) {
console.error(
`No result received. Status: ${result.errorCode}. Error: ${result.error}`
);
} else {
console.info(`Data received: '${JSON.stringify(result.result)}'.`);
}
};

Example Output (Success)

{
"isSuccessful": true
}

Common Use Cases

  • Initiating a Business Flow: When you need to start a predefined business flow, such as fetching user aliases or adding new records (e.g., aliases or consent).
  • Triggering Backend Workflows: This method can be used to start workflows that may be processed by a backend engine, depending on the business requirements and configuration.
  • Passing Payloads: You can provide additional data (payload) when starting a flow, which can include metadata, user inputs, or other relevant parameters required by the flow.

Method: startFlowAndWaitData

The startFlowAndWaitData() method initiates a business flow for a contact and waits for the flow to complete, returning the resulting data. This function is particularly useful when you need the flow to return some data or result after it finishes executing.

  • Purpose: The purpose of this method is to start a flow for a contact and wait for a response or data. It is typically used when you need to trigger a process that returns some data, such as revoking consent or listing consents, and you want to block until the result is available.

  • Parameters:

    • contactFilter: ContactFilterModel — The search criteria used to identify the contact (connection). This model can contain:

      • id?: string — The unique identifier of the contact.
      • alias?: AliasIdentifier — The alias of the contact.
      • did?: string — The decentralized identifier (DID) of the contact.
    • args: { url: string, payload?: any } — The arguments required for starting the flow:

      • url: string — The URL endpoint where the flow is triggered.
      • payload?: any — (Optional) Additional data or parameters required for the flow.
    • timeoutInSeconds?: number — (Optional) The maximum amount of time (in seconds) to wait for the flow to return data before timing out.

  • Returns: Promise<OperationDataResult<any>> — Resolves to an OperationDataResult object that contains the result data of the flow if successful. If unsuccessful, it returns an error message with an optional timeout error.

Usage Example

  1. Revoke Consent

This example demonstrates how to use startFlowAndWaitData() to revoke consent for a specific contact.

export const revokeConsentApi = async (consentId: string): Promise<boolean> => {
const agent = await initializeAgent();
if (!agent) {
throw new Error("Agent not initialized");
}
let response = await agentInstance.contactManager.getHome();
let connection = response.result;

console.log("Revoke Consent for:", consentId);
const url = "consent/revoke";

// Start the flow to revoke consent and wait for data
const result = await agent.contactManager.startFlowAndWaitData(
{ id: connection?.id },
{
url: url,
payload: { consentId: consentId },
}
);

console.log("Revoke consent result:", result);
if (!result.isSuccessful) {
console.error(
`Revoke Consent Failed. Status: ${result.errorCode}. Error: ${result.error}`
);
return false;
} else {
console.info(`Revoke consent success: '${JSON.stringify(result.result)}'.`);
return true;
}
};
  1. List Consents

This example demonstrates how to use startFlowAndWaitData() to list all consents for a contact.

export const listConsents = async (): Promise<any> => {
const agent = await initializeAgent();
if (!agent) {
throw new Error("Agent not initialized");
}

let response = await agentInstance.contactManager.getHome();
let connection = response.result;

const url = "consent/list";

// Start the flow to list consents and wait for the result
const result = await agent.contactManager.startFlowAndWaitData(
{ id: connection?.id },
{
url: url,
payload: {},
}
);

if (!result.isSuccessful) {
console.error(
`No result received. Status: ${result.errorCode}. Error: ${result.error}`
);
return undefined;
} else {
const dataObject = JSON.parse(result.result);
console.log("Received data:", dataObject.Result.Result);
return dataObject.Result.Result;
}
};
{
"isSuccessful": true,
"result": {
"message": "Consent successfully revoked."
}
}

Common Use Cases

  • Triggering a Flow and Waiting for Data: When you need to start a flow for a contact and retrieve data (e.g., fetching consent lists, revoking consent), this method waits until the process completes and returns the resulting data.
  • Handling Asynchronous Workflows: Useful in situations where flows take time to process, allowing you to wait for the result, such as in long-running or backend-heavy processes.
  • Timeout Handling: You can specify a timeout to prevent the method from waiting indefinitely, ensuring the method fails gracefully after a specified period.
X

Graph View